package red.lixiang.service.impl;

import red.lixiang.dao.ProductDAO;
import red.lixiang.dao.PromotionDAO;
import red.lixiang.model.BaseInfo;
import red.lixiang.model.Product;
import red.lixiang.model.ProductPromotion;
import red.lixiang.service.ListService;
import red.lixiang.utils.IS_ListUtils;
import red.lixiang.utils.ProductUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static red.lixiang.base.APPCONST.TYPE_HOT;
import static red.lixiang.base.ProductConfig.productNameMap;

@Repository
public class ListServiceImpl  implements ListService{

    @Autowired
    private ProductDAO productDAO;

    @Autowired
    private PromotionDAO promotionDAO;


    @Override
    public BaseInfo getProductByKeyWord(String keyWord) {
        BaseInfo baseInfo = new BaseInfo("0","ok");
        //先匹配关键词
        Map<String ,String> map = productNameMap;
        List<String> words = ProductUtils.getKeyWords(keyWord);

        List<Product> productsList = productDAO.getAllProduct();

        //筛选出匹配的项
        List<Product> avaliableProduct = productsList.stream().filter(product -> {
            for (String word : words) {
                if (product.getProductName().contains(word)) {
                    return true;
                }
            }
            return false;
        }).filter(IS_ListUtils.distinctByKey(Product::getProductId)).collect(Collectors.toList());
        baseInfo.setObject(avaliableProduct);

        return baseInfo;
    }

    @Override
    public BaseInfo getIndexProduct() {


        return this.getPromotionProductByType(TYPE_HOT);
    }

    @Override
    public BaseInfo getPromotionProductByType(String type) {

        BaseInfo baseInfo = new BaseInfo("0","ok");

        ProductPromotion productPromotion = new ProductPromotion();
        productPromotion.setPromotionType(Integer.valueOf(type));
        List<ProductPromotion> promotions = promotionDAO.getPromotion(productPromotion);
        //然后根据ProductId获取产品
        for (ProductPromotion promotion : promotions) {
            Product product =   productDAO.getProductByProductId(promotion.getProductId()).get(0);
            promotion.setProduct(product);
        }
        List<Product> products = promotions.stream().map(ProductPromotion::getProduct).collect(Collectors.toList());

        Map<String , Object > map = new HashMap<>();
        map.put("products",products);
        map.put("promotions",promotions);

        baseInfo.setObject(map);

        return baseInfo;
    }

}
